#-*-coding:utf-8-*-
'''
This module is used to encrypt the pixels in jpg format pictures.
'''
import jpgmodule

class Encrypt:
    '''
    To Encrypt the pixels.
    '''
    def __init__(self):
        self.jpg = ''       #to store the jpg module.

    def OpenJpg(self,pathname):
        '''
        To open the plain jpg image.
        '''
        self.jpg = jpgmodule.myJpg()
        re = self.jpg.openfile(pathname)   #open the file
        if re == True:
            return True
        else:
            #self.jpg = ''
            return False    #not a jpg image. but the program can deal with

    def Permutation(self):
        '''
        This module is used to switch the pixels.
        '''
        pass
        if self.ldata:
            self.ldata.reverse()

    def Substitution(self):
        '''
        replace the pixels
        '''
        k = list()
        for c in self.ldata:
            k.append((255 - c[0],255 - c[1],255 - c[2]))
        self.ldata = k[:]

    def Encryption(self,srcpathname,destpathname):
        '''
        Encrypt the picture.
        '''
        c = self.OpenJpg(srcpathname)
        c = self.jpg.getData()
        if not c:
            return False
        else:
            #get the data.
            self.ldata = list(self.jpg.imagedata)
            self.Permutation()
            self.Substitution()
            self.jpg.putData(self.ldata)
            self.jpg.SaveAs(destpathname)
            return True
    def Decryption(self,srcpathname,destpathname):
        '''
        Decrypt the picture
        '''
        c = self.OpenJpg(srcpathname)
        c = self.jpg.getData()
        if not c:
            return False
        else:
            self.ldata = list(self.jpg.imagedata)
            self.Substitution()
            self.Permutation()
            self.jpg.putData(self.ldata)
            self.jpg.SaveAs(destpathname)
            return True

    def test(self):
        '''
        Test the module.
        '''
        self.Encryption('/home/hucheng/workspace/graduateproject/image-compress-encrypt/res/lina.jpg','/home/hucheng/workspace/graduateproject/image-compress-encrypt/res/en.jpg')
        self.Decryption('/home/hucheng/workspace/graduateproject/image-compress-encrypt/res/en.jpg','/home/hucheng/workspace/graduateproject/image-compress-encrypt/res/de.jpg')

if __name__ == '__main__':
    c = Encrypt()
    c.test()
